package cn.tedu.controller;

import cn.tedu.pojo.Product;
import cn.tedu.pojo.Types;
import cn.tedu.service.ProductService;
import cn.tedu.service.TypesService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

@Controller
public class ProductController {
    @Autowired
    ProductService productService;
    @Autowired
    TypesService typesService;
    //传统分页
    @RequestMapping("/productList")
    public String productList(
            @RequestParam(value = "name",defaultValue = "") String name,
            @RequestParam(value = "isHot",defaultValue = "2") Integer isHot,
            @RequestParam(value = "typeId",defaultValue = "-1") Integer typeId,
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            Model model){

        //页码 pageNum  每页显示记录数 pageSize
        int pageSize = 3;

        //查询product集合数据
        //List <Product> products = productService.selectProductByMH(name, isHot, typeId);

        //查询Types数据
        List <Types> types = typesService.findTypes();
        //总的记录数
        int num = productService.selectProductByMH(name, isHot, typeId).size();
        //总页数
        int total = num%pageSize ==0 ?num/pageSize:num/pageSize+1;

        //分页功能
        List <Product> products = productService.selectProductByPage(name, isHot, typeId, pageNum, pageSize);

        //model对象存数据
        model.addAttribute("products",products);
        model.addAttribute("types",types);

        model.addAttribute("name",name);
        model.addAttribute("isHot",isHot);
        model.addAttribute("typeId",typeId);

        model.addAttribute("pageNum",pageNum);
        model.addAttribute("total",total);

        return "product_list";
    }

    //基于mybatis的分页插件
    @RequestMapping("/productListPageHelper")
    public String productListPageHelper(
            @RequestParam(value = "name",defaultValue = "") String name,
            @RequestParam(value = "isHot",defaultValue = "2") Integer isHot,
            @RequestParam(value = "typeId",defaultValue = "-1") Integer typeId,
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            Model model
    ){
        //每页显示记录数
        int pageSize = 3;
        //分页插件
        PageHelper.startPage(pageNum,pageSize);
        //查询product集合数据
        List <Product> products = productService.selectProductByMH(name, isHot, typeId);
        //查询types数据
        List <Types> types = typesService.findTypes();
        //把product集合数据构造到pageInfo对象中
        PageInfo<Product> pageInfo = new PageInfo(products);

        //model对象存数据
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("types",types);

        model.addAttribute("name",name);
        model.addAttribute("isHot",isHot);
        model.addAttribute("typeId",typeId);

        //model.addAttribute("pageNum",pageNum);

        return "product_list_pageHelper";
    }

    //删除
    @RequestMapping("/delete")
    public String delete(int id){
        productService.deleteById(id);

        //重定向
        return "redirect:/productListPageHelper.do";
    }

    //跳转到add.jsp 页面
    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        //查询types数据
        List <Types> types = typesService.findTypes();

        model.addAttribute("types",types);

        return "add";
    }
    //登录
    @RequestMapping("/login")
    public String login(int id){
        productService.deleteById(id);

        //重定向
        return "redirect:/productListPageHelper.do";
    }
    //跳转到login.jsp页面
    @RequestMapping("/toAdd")
    public String toLogin(Model model){
        //查询types数据
        List <Types> types = typesService.findTypes();

        model.addAttribute("types",types);

        return "login";
    }
    //添加
    @RequestMapping("/add")
    public String add(Product product){
        productService.addProduct(product);

        return "redirect:/productListPageHelper.do";
    }

    //跳转到update.jsp 页面
    @RequestMapping("/toUpdate")
    public String toUpdate(Integer id,Model model){
        //根据id查询数据
        Product product = productService.selectProductById(id);
        //查询types数据
        List <Types> types = typesService.findTypes();

        model.addAttribute("types",types);
        model.addAttribute("product",product);

        return "update";
    }

    @RequestMapping("/update")
    public String update(Product product){
        productService.updateProduct(product);
        return "redirect:/productListPageHelper.do";
    }

    //图片上传
    @RequestMapping("/upload")
    @ResponseBody
    public String uploadImage(@RequestParam(value = "myfile",required = false)MultipartFile file,
                              HttpSession session){
        JSONObject json = new JSONObject();
        //1.获取上传的文件地址
        String realpath =  session.getServletContext().getRealPath(File.separator+"/image");
        System.out.println("realpath----------"+realpath);
        //2.获取上传文件的名称
        String oldName = file.getOriginalFilename();
        //3.获取上传文件后缀名
        String suffix = FilenameUtils.getExtension(oldName);
        //4.设置上传文件的大小
        int fileSize = 500000;  //500KB
        if(file.getSize()>fileSize){
            json.put("error","文件大小超过500K");
        }else{
            if(suffix.equalsIgnoreCase("jpg") ||
               suffix.equalsIgnoreCase("jpeg") ||
               suffix.equalsIgnoreCase("png") ||
                suffix.equalsIgnoreCase("gif")){
                //5.重新遍历文件名称 不让文件名重复
                String newName = System.currentTimeMillis()+"."+suffix;
                //6.创建file对象
                File finalFile = new File(realpath,newName);
                if(!finalFile.exists()){
                    finalFile.mkdirs();  //如果不存在则创建
                }
                //7.执行上传
                try {
                    file.transferTo(finalFile);
                } catch (IOException e) {
                    json.put("error","上传异常!");
                }
                //8.把上传文件的名称封装到json格式传递到浏览器
                json.put("url","/image/"+newName);
            }
        }
        return json.toJSONString();
    }
}
